package Day2025_01_18;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoClient {
    // 声明一个DatagramSocket对象
    private DatagramSocket socket;
    // 声明服务器IP
    private String serverIp;
    // 声明服务器端口号
    private int serverPort;

    // 通过构造方法指定服务器IP和端口号
    public UDPEchoClient(String serverIp, int serverPort) throws SocketException {
        // 初始化DatagramSocket对象
        this.socket = new DatagramSocket();
        // 指定服务器端口号和IP
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    /**
     * 客户端服务
     */
    public void start () throws IOException {
        System.out.println("客户端已启动.");
        // 循环处理客户端的输入
        while (true) {
            System.out.println("->");
            // 定义Scanner
            Scanner scanner = new Scanner(System.in);
            // 1.获取用户输入
            String request = scanner.nextLine();
            if (request == null || request.isEmpty()) {
                System.out.println("不能输入空字符.");
                continue;
            }
            // 2.创建目标的SocketAddress对象
            SocketAddress address = new InetSocketAddress(serverIp, serverPort);
            // 3.定义一个用于包装用户请求的数据的DatagramPacket
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    0, request.getBytes().length, address);
            // 4.发送真实的数据到服务器
            socket.send(requestPacket);
            // 5.用DatagramPacket接收服务器响应的数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            // 6.接收数据
            socket.receive(responsePacket);
            // 7.解析数据得到的响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            // 8. 打印相应结结结果
            System.out.printf("request = %s, response = %s\n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient client = new UDPEchoClient("127.0.0.1", 8888);
        client.start();
    }
}












